<template>
  <div>
    <el-from>
      <el-tabs type="border-card" @tab-change="tabChange" v-model="nameData">
        <el-tab-pane label="培训科目" name="trainSubject">
          <el-button type="primary" @click="addFN">新建科目</el-button>
          <el-button type="success" @click="importTrainFN">导入科目</el-button>
          <br />
          <br />

          <el-table :data="projectList">
            <!-- <el-table-column type="index" /> -->
            <el-table-column
              label="序号"
              width="80"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="科目名称"
              min-width="100"
              align="center"
              prop="projectName"
            ></el-table-column>
            <el-table-column
              label="科目费用"
              min-width="200"
              align="center"
              prop="cost"
            ></el-table-column>
            <el-table-column
              label="必报科目"
              min-width="120"
              align="center"
              prop="isNecessary"
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.isNecessary == 1"
                  type="success"
                  class="mx-1"
                  effect="dark"
                  round
                  >是
                </el-tag>
                <el-tag v-else type="success" class="mx-1" effect="plain" round
                  >否
                </el-tag>
              </template></el-table-column
            >
            <el-table-column label="操作" min-width="120" align="center">
              <template #default="scope">
                <el-button type="text" icon="Edit" @click="update(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" icon="Plus" @click="moveUp(scope.row)"
                  >上移</el-button
                >
                <el-button type="text" icon="Plus" @click="moveDown(scope.row)"
                  >下移</el-button
                >
                <el-button type="text" icon="Delete" @click="delFN(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="考试科目" name="examSubject">
          <el-button type="primary" @click="examAddFN">新建科目</el-button>
          <el-button type="success" @click="importExamFN">导入科目</el-button>
          <br />
          <br />

          <el-table :data="examList">
            <el-table-column
              label="序号"
              width="80"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="科目名称"
              min-width="100"
              align="center"
              prop="projectName"
            ></el-table-column>
            <el-table-column
              label="科目费用"
              min-width="200"
              align="center"
              prop="cost"
            ></el-table-column>
            <el-table-column
              label="必报科目"
              min-width="120"
              align="center"
              prop="isNecessary"
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.isNecessary == 1"
                  type="success"
                  class="mx-1"
                  effect="dark"
                  round
                  >是
                </el-tag>
                <el-tag v-else type="success" class="mx-1" effect="plain" round
                  >否
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120" align="center">
              <template #default="scope">
                <el-button type="text" icon="Edit" @click="updateFN(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" icon="Plus" @click="moveUpFN(scope.row)"
                  >上移</el-button
                >
                <el-button
                  type="text"
                  icon="Plus"
                  @click="moveDownFN(scope.row)"
                  >下移</el-button
                >
                <el-button
                  type="text"
                  icon="Delete"
                  @click="deleteFN(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <br />
      <br />
      <br />
      <el-row justify="center">
        <el-button type="primary" v-if="route.query.id" @click="shangFN(id)"
          >上一步</el-button
        >
        <el-button type="primary" @click="xiaFN(id)">下一步</el-button>
      </el-row>
    </el-from>

    <!-- 弹框 -->
    <el-dialog
      v-model="showDialog"
      width="30%"
      append-to-body
      center
      draggable
      @close="close"
      v-if="showDialog"
      :title="addForm.id ? '编辑科目' : '新建科目'"
    >
      <el-form ref="Dialog" :rules="rules" :model="addForm" label-width="120px">
        <el-form-item label="科目名称：" prop="projectName">
          <el-input v-model="addForm.projectName" />
        </el-form-item>
        <el-form-item label="科目费用：" prop="cost">
          <el-input type="number" v-model="addForm.cost" />
        </el-form-item>

        <el-form-item label="是否必报科目：" prop="isNecessary">
          <el-radio-group v-model="addForm.isNecessary">
            <el-radio :label="1" size="large">是</el-radio>
            <el-radio :label="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFN">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹框 -->
    <el-dialog
      v-model="showImport"
      width="30%"
      append-to-body
      center
      draggable
      @close="closeFN"
      v-if="showImport"
      :title="addForm.id ? '编辑科目' : '新建科目'"
    >
      <el-tree
        ref="treeRef"
        :data="importList"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importFN">导 入</el-button>
          <el-button type="primary" @click="toggleSelection">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TrainSet">
import {
  trainSetList,
  trainSetAdd,
  trainSetUpdate,
  trainSetMove,
  trainSetDel,
  trainSetImportList,
  trainSetImport,
} from "@/api/train/trainSet.js";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const treeRef = ref();
const Dialog = ref();
const examList = ref();
const projectList = ref();
const showDialog = ref(false);
const showImport = ref(false);
const importList = ref();
const nameData = ref("trainSubject");
const emit = defineEmits(["xiaFN"]);
const props = defineProps({
  id: {},
  projectId: {},
});
const id = ref(props.id);
const projectId = ref(props.projectId);
const data = reactive({
  user: {
    trainId: props.id,
  },
  addForm: {},
  rules: {
    projectName: [
      { required: true, message: "培训名称不能为空", trigger: "blur" },
    ],
    cost: [{ required: true, message: "培训费用不能为空", trigger: "blur" }],
    isNecessary: [
      {
        required: true,
        message: "请选择是否必报科目",
        trigger: "change",
      },
    ],
  },
});
const { user, addForm, rules } = toRefs(data);
if (route.query.projectId) {
  projectId.value = route.query.projectId;
}

// 获取数据
initData();
async function initData() {
  user.value.trainId = id.value;
  if (route.query.id) {
    user.value.trainId = route.query.id;
  }
  let res = await trainSetList(user.value);
  examList.value = res.examList;
  projectList.value = res.projectList;
  console.log(res);
}

// 下一步
function xiaFN(id) {
  emit("xiaFN", 2, id, projectId.value);
  clearInterval(timer.value);
}

function shangFN(id) {
  emit("xiaFN", 0, id, projectId.value);
  clearInterval(timer.value);
}

// 新增按钮
function addFN() {
  addForm.value = {};
  showDialog.value = true;
}

// 返回
function goBack() {
  emit("goBack");
}

// tab栏切换
function tabChange(name) {
  nameData.value = name;
}

// 保存
async function submitFN() {
  try {
    await Dialog.value.validate();
  } catch (error) {
    console.log(error);
    return false;
  }

  if (nameData.value == "trainSubject") {
    // 培训科目
    addForm.value.trainOrExam = 0;
    if (addForm.value.id) {
      // 修改
      await trainSetUpdate(addForm.value).then(() => {});
    } else {
      // 新增
      addForm.value.trainId = user.value.trainId;
      await trainSetAdd(addForm.value);
    }
    close();
  } else {
    // 考试科目
    addForm.value.trainOrExam = 1;
    if (addForm.value.id) {
      // 修改
      console.log(addForm.value);

      await trainSetUpdate(addForm.value);
    } else {
      // 新增
      addForm.value.trainId = user.value.trainId;
      await trainSetAdd(addForm.value);
    }
    close();
  }
}

// 关闭弹框
function close() {
  showDialog.value = false;
  initData();
  addForm.value = {};
}

// 关闭导入弹框
function closeFN() {
  showImport.value = false;
  initData();
  addForm.value = {};
}
// 编辑
function update(row) {
  addForm.value = {};
  addForm.value.trainOrExam = 0;
  showDialog.value = true;
  addForm.value = row;
}

// 上移
async function moveUp(row) {
  addForm.value.trainOrExam = 0;
  addForm.value = row;
  addForm.value.flag = 0;
  await trainSetMove(addForm.value);
  initData();
}

// 下移
async function moveDown(row) {
  addForm.value.trainOrExam = 0;
  addForm.value = row;
  addForm.value.flag = 1;
  await trainSetMove(addForm.value);
  initData();
}

const timer = ref();
// 删除
function delFN(row) {
  proxy.$modal
    .confirm('是否确认删除科目名称为"' + row.projectName + '"的数据项？')
    .then(function () {
      addForm.value.trainOrExam = 0;
      addForm.value = row;
      trainSetDel(addForm.value);
    })
    .then((res) => {
      timer.value = setTimeout(() => {
        initData();
      }, 500);
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 考试新增按钮
function examAddFN() {
  showDialog.value = true;
}

// 考试编辑
function updateFN(row) {
  addForm.value = {};
  addForm.value = row;
  showDialog.value = true;
}

// 考试上移
async function moveUpFN(row) {
  addForm.value.trainOrExam = 1;
  addForm.value = row;
  addForm.value.flag = 0;
  await trainSetMove(addForm.value);
  initData();
}

// 考试下移
async function moveDownFN(row) {
  addForm.value.trainOrExam = 1;
  addForm.value = row;
  addForm.value.flag = 1;
  await trainSetMove(addForm.value);
  initData();
}

// 考试删除
function deleteFN(row) {
  proxy.$modal
    .confirm('是否确认删除科目名称为"' + row.projectName + '"的数据项？')
    .then(function () {
      addForm.value.trainOrExam = 1;
      addForm.value = row;
      console.log(addForm.value);
      trainSetDel(addForm.value);
    })
    .then(() => {
      initData();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 树形控件数据绑定
const defaultProps = {
  children: "projectVoList",
  label: "projectName",
};

// 培训导入科目
async function importTrainFN() {
  showImport.value = true;
  addForm.value.projectId = projectId.value;
  addForm.value.flag = 0;
  let res = await trainSetImportList(addForm.value);
  importList.value = res.data;
  console.log(res);
}

// 考试导入科目
async function importExamFN() {
  showImport.value = true;
  addForm.value.projectId = projectId.value;
  addForm.value.flag = 1;
  let res = await trainSetImportList(addForm.value);
  importList.value = res.data;
  console.log(res);
}

// 导入
async function importFN() {
  let res = treeRef.value.getCheckedNodes();
  res = JSON.parse(JSON.stringify(res));
  let arr = res.filter((item) => {
    return item.id;
  });
  let arrList = arr.map((item) => {
    return item.id;
  });
  addForm.value.trainId = user.value.trainId;
  addForm.value.projectIds = arrList;
  if (nameData.value == "trainSubject") {
    // 培训
    addForm.value.flag = 0;
  } else {
    // 考试
    addForm.value.flag = 1;
  }

  await trainSetImport(addForm.value);
  closeFN();
}

// 取消
const toggleSelection = () => {
  treeRef.value.setCheckedKeys([]);
  closeFN();
};
</script>

<style scope></style>
